import 'dart:convert';
import 'dart:io';
import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:full_display/common/qxp_color.dart';
import 'package:full_display/common/qxp_style.dart';
import 'package:full_display/common/url_path.dart';
import 'package:full_display/generated/l10n.dart';
import 'package:full_display/page/single/single_add_wenzi_page.dart';
import 'package:full_display/page/single/single_api.dart';
import 'package:full_display/provide/cmd_provider.dart';
import 'package:full_display/routers/route_name.dart';
import 'package:full_display/unit/asset_utils/asset_utils.dart';
import 'package:full_display/unit/log/log_util.dart';
import 'package:full_display/unit/navigation/navigation_util.dart';
import 'package:full_display/unit/screen/screen_util1.dart';
import 'package:full_display/unit/screen/screen_utility.dart';
import 'package:full_display/unit/toast/toast_util.dart';
import 'package:full_display/unit/web_socket/web_sockect_utils.dart';
import 'package:full_display/unit/widgets/button/click_animated.dart';
import 'package:full_display/unit/widgets/widget_dialog/add_media_dialog.dart';
import 'package:full_display/unit/widgets/widget_dialog/clock_dialog.dart';
import 'package:full_display/unit/widgets/widget_dialog/crop_image_dialog.dart';
import 'package:full_display/unit/widgets/widget_dialog/crop_media_dialog.dart';
import 'package:full_display/unit/widgets/widget_dialog/widget_dialog.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';
import 'package:dio/dio.dart';
import 'package:video_player/video_player.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class MedisListWidget extends StatefulWidget {
  final List list;
  final double h;
  VoidCallback clearData;
  final String info;
  MedisListWidget({
    Key? key,
    required this.list,
    required this.h,
    required this.clearData,
    required this.info,
  }) : super(key: key);

  @override
  State<MedisListWidget> createState() => _MedisListWidgetState();
}

class _MedisListWidgetState extends State<MedisListWidget> {
  ScrollController _scrollController = ScrollController();
  VideoPlayerController? _playerController;
  bool isShow = false;
  bool isDelete = false;
  int currentindex = 0;
  BuildContext? curContext;
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    curContext = context;
    return Container(
      decoration: const BoxDecoration(
        color: ColorPlate.backgroundOpacity5,
        borderRadius: BorderRadius.all(Radius.circular(12.0)),
      ),
      child: Padding(
        padding: EdgeInsets.fromLTRB(20.0.W, 10.0.H, 20.0.W, 20.0.H),
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  S.of(context).meitineirong,
                  style: StandardTextStyle.textWhite16Style,
                ),
                TextButton(
                    onPressed: () {
                      widget.clearData();
                    },
                    child: Text(widget.info))
              ],
            ),
            Padding(
              padding: EdgeInsets.only(bottom: 15.0.H),
              child: Container(
                height: 1,
                color: ColorPlate.backgroundOpacity20,
              ),
            ),
            Container(
              // height: (((widget.list.length - 1) / 4).truncateToDouble() + 1) *
              //             86.0.W >
              //         300
              //     ? 300
              //     : (((widget.list.length - 1) / 4).truncateToDouble() + 1) *
              //         86.0.W,
              height: widget.h,
              child: GridView.builder(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 4,
                    crossAxisSpacing: 2.0.W,
                    mainAxisSpacing: 2.0.W),
                scrollDirection: Axis.vertical,
                controller: _scrollController,
                itemCount: widget.list.length + 1,
                itemBuilder: (context, index) {
                  double w = (ScreenUtil1.screenWidth - 86.0.W) / 4.0;
                  if (index == widget.list.length) {
                    return InkWell(
                      child: ClickAnimated(
                        child: SizedBox(
                          height: w,
                          width: w,
                          child: Image.asset(
                              height: w,
                              width: w,
                              AssetUtils.getAsset2Image("icon_increase")),
                        ),
                        onTap: () {
                          setState(() {
                            clickdialog();
                          });
                        },
                      ),
                    );
                  } else {
                    return GestureDetector(
                      onLongPress: () {
                        setState(() {
                          print("=============");
                          currentindex = index;
                          isDelete = true;
                        });
                      },
                      child: Stack(
                        children: [
                          InkWell(
                            child: ClickAnimated(
                              child: SizedBox(
                                height: w,
                                width: w,
                                child: Image(
                                  image: CachedNetworkImageProvider(
                                      UrlPath.MEDIA_URL +
                                          widget.list[index]['thum_path'],
                                      cacheKey: widget.list[index]
                                          ['file_name']),
                                ),
                                // Image.network(
                                //     height: w,
                                //     width: w,
                                //     UrlPath.MEDIA_URL +
                                //         widget.list[index]['thum_path']),
                              ),
                              onTap: () {
                                setState(() {
                                  isDelete = false;
                                });
                                WebSocketUtils().sendMessage(6,
                                    content: widget.list[index]['file_id']);
                              },
                            ),
                          ),
                          (isDelete == true && currentindex == index)
                              ? InkWell(
                                  onTap: () {
                                    print(
                                        "===============>${widget.list[index]['file_id']}");
                                    isDelete = false;
                                    showCupertinoAlertDialog(
                                        context, widget.list[index]['file_id']);
                                  },
                                  child: Container(
                                    color: ColorPlate.backgroundOpacity75,
                                    height: w,
                                    width: w,
                                    child: Image.asset(
                                        AssetUtils.getAsset2Image('delete')),
                                  ),
                                )
                              : Container(),
                        ],
                      ),
                    );
                  }
                },
              ),
            ),
            //视频的展示
            // Container(
            //   width: 200,
            //   height: 200,
            //   child: isShow == true ? _previewVideo() : Container(),
            // )
          ],
        ),
      ),
    );
  }

  void showCupertinoAlertDialog(BuildContext context, int fileid) {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return CupertinoAlertDialog(
            content: Column(
              children: <Widget>[
                Align(
                  alignment: Alignment(0, 0),
                  child: Text(S.of(context).are_you_delete),
                ),
              ],
            ),
            actions: <Widget>[
              CupertinoDialogAction(
                child: Text(S.of(context).quxiao),
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
              CupertinoDialogAction(
                child: Text(S.of(context).queding),
                onPressed: () {
                  Navigator.pop(context);
                  WebSocketUtils().sendCustomMessage(67, content: fileid);
                },
              ),
            ],
          );
        });
  }

  void clickdialog() {
    showDialog(
      context: context,
      barrierDismissible: true,
      builder: (context) {
        return AddMediaDialog(
          // tapAction: filePath,
          tapAction: (int index, BuildContext context1) {
            btnListdialog(index, curContext!);
          },
        );
      },
    );
  }

  void btnListdialog(int index, BuildContext context) {
    Navigator.pop(context);
    if (index == 0) {
      isVideo = false;
      _onImageButtonPressed(ImageSource.gallery, context: context);
    } else if (index == 1) {
      isVideo = true;
      _onImageButtonPressed(ImageSource.gallery, context: context);
    } else {
      NavigationUtil.getInstance().pushPage(
        context,
        RouteNames.singleAddWenziPage,
        widget: const SingleWenziWidget(),
      );
    }
  }

  final ImagePicker _picker = ImagePicker();
  bool isVideo = false;

  Future<void> _onImageButtonPressed(ImageSource source,
      {BuildContext? context, bool isMultiImage = false}) async {
    if (isVideo) {
      final List<AssetEntity>? result = await AssetPicker.pickAssets(
        context!,
        pickerConfig: const AssetPickerConfig(
          maxAssets: 1,
          requestType: RequestType.video,
          selectedAssets: [],
          themeColor: ColorPlate.transparent,
          // textDelegate: const EnglishAssetPickerTextDelegate(),
        ),
      );
      var asset = result![0];
      print("============>${asset.file}======${asset.originFile}");
      if (result != null) {}
      final File file = await asset.file as File;
      if (file != null) {
        showDialog(
          barrierDismissible: false,
          context: context!,
          builder: (context) {
            return DialogWidget(
              contentWidget: CropMediaDialog(
                path: file!.path,
              ),
            );
          },
        );
      }

      // final XFile? file = await _picker.pickVideo(
      //     source: source, maxDuration: const Duration(seconds: 10000));
      // // if (file != null) {
      // //   Navigator.pop(context!);
      // // await _playVideo(file);
      // // tapAction(file);
      // // }

      // // updateVideo(file!.path, context!);
      // if (file != null) {
      //   showDialog(
      //     barrierDismissible: false,
      //     context: context!,
      //     builder: (context) {
      //       return DialogWidget(
      //         contentWidget: CropMediaDialog(
      //           path: file!.path,
      //         ),
      //       );
      //     },
      //   );
      // }
    } else if (isMultiImage) {
      final List<XFile> pickedFileList = await _picker.pickMultiImage();

      print("-------->${pickedFileList}");
    } else {
      final XFile? pickedFile = await _picker.pickImage(source: source);
      if (pickedFile != null) {
        showDialog(
          barrierDismissible: false,
          context: context!,
          builder: (context) {
            return DialogWidget(
              contentWidget: CropImageDialog(
                path: pickedFile.path,
              ),
            );
          },
        );

        // _cropImage(pickedFile);
        // Uint8List file_buffer = await pickedFile.readAsBytes();
        // String base64 = base64Encode(file_buffer);
        // print("leng========>${base64.length}");
        // Uint8List array_buffer = base64Decode(base64);
        // print("array_buffer leng========>${array_buffer.length}");
        // int packLength = 32768;
        // if (array_buffer != null) {
        //   int pack_count = (array_buffer.length / packLength).ceil();
        //   print("pack_count------->${pack_count}");
        //   WebSocketUtils().sendCustomMessage(66,
        //       content: {'type': '1', 'count': pack_count});
        //   if (pack_count > 0) {
        //     ByteData buffF = ByteData(packLength);

        //     for (var i = 0; i < pack_count; i++) {
        //       if (i == (pack_count - 1)) {
        //         //最后一个数据包
        //         Uint8List buffList = array_buffer.sublist(i * packLength);
        //         buffF = ByteData.view(buffList.buffer);
        //         bufferData(buffF, i, pack_count);
        //       } else {
        //         Uint8List buffList =
        //             array_buffer.sublist(i * packLength, (i + 1) * packLength);
        //         buffF = ByteData.view(buffList.buffer);
        //         bufferData(buffF, i, pack_count);
        //       }
        //     }
        //   }
        // }
      }
    }
  }

  Future<void> _cropImage(XFile? pickedFile) async {
    if (pickedFile != null) {
      final croppedFile = await ImageCropper().cropImage(
        sourcePath: pickedFile.path,
        compressFormat: ImageCompressFormat.jpg,
        compressQuality: 100,
        uiSettings: [
          AndroidUiSettings(
              toolbarTitle: 'Cropper',
              toolbarColor: Colors.deepOrange,
              toolbarWidgetColor: Colors.white,
              initAspectRatio: CropAspectRatioPreset.original,
              lockAspectRatio: false),
          IOSUiSettings(
            title: 'Cropper',
          ),
          WebUiSettings(
            context: context,
            presentStyle: CropperPresentStyle.dialog,
            boundary: const CroppieBoundary(
              width: 520,
              height: 520,
            ),
            viewPort:
                const CroppieViewPort(width: 480, height: 480, type: 'circle'),
            enableExif: true,
            enableZoom: true,
            showZoomer: true,
          ),
        ],
      );
      if (croppedFile != null) {
        setState(() {
          // _croppedFile = croppedFile;
        });
      }
    }
  }

  //发送单机数据包
  void bufferData(ByteData buff, index, packCount) {
    int num = 15 + buff.lengthInBytes; //每个包的数据总长度
    Uint8List bufF = Uint8List(num);

    ByteData dataView = ByteData.view(bufF.buffer);
    var i = 0;

    dataView.setUint8(i, 0xfa);
    i++;
    dataView.setUint8(i, 0xf0);
    i++;
    dataView.setUint8(i, 66); //cmd
    i++;
    dataView.setUint8(i, 0); //number
    i++;
    dataView.setUint32(i, packCount, Endian.little); //count
    i += 4;
    dataView.setUint32(i, index, Endian.little); //index
    i += 4;
    if (index == packCount - 1) {
      dataView.setUint16(i, buff.lengthInBytes, Endian.little);
    } else {
      dataView.setUint16(i, 32768, Endian.little);
    }
    i += 2;
    ByteData dataView_data = ByteData.view(buff.buffer);
    // console.log('byteLength=', buff.byteLength);
    int k = 0;
    for (var j = 0; j < buff.lengthInBytes; j++) {
      k = j;
      dataView.setUint8(i + j, dataView_data.getUint8(j));
    }
    i = i + k + 1;
    dataView.setUint8(i, 254);
    print("12------${bufF.sublist(0, 50)}");
    print("123------${bufF.sublist(bufF.length - 5)}");
    print(bufF.lengthInBytes);
    WebSocketUtils()
        .sendCustomMessage(66, content: {"type": "2", "data": bufF});
  }

  //****************************************视频显示   目前废弃 ********************************** */

  void filePath(XFile file) {
    if (file != null) {
      _playerController = VideoPlayerController.file(File(file.path));
      // In web, most browsers won't honor a programmatic call to .play
      // if the video has a sound track (and is not muted).
      // Mute the video so it auto-plays in web!
      // This is not needed if the call to .play is the result of user
      // interaction (clicking on a "play" button, for example).
      const double volume = 1.0;
      _playerController?.setVolume(volume);
      _playerController?.initialize();
      _playerController?.setLooping(true);
      _playerController?.play();
      setState(() {
        isShow = true;
      });
    }
  }

  Widget _previewVideo() {
    if (_playerController == null) {
      return const Text(
        'You have not yet picked a video',
        textAlign: TextAlign.center,
      );
    }
    return Container(
      padding: const EdgeInsets.all(10.0),
      color: Colors.red,
      child: AspectRatioVideo(_playerController),
    );
  }
}

class AspectRatioVideo extends StatefulWidget {
  const AspectRatioVideo(this.controller, {super.key});

  final VideoPlayerController? controller;

  @override
  AspectRatioVideoState createState() => AspectRatioVideoState();
}

class AspectRatioVideoState extends State<AspectRatioVideo> {
  VideoPlayerController? get controller => widget.controller;
  bool initialized = false;

  void _onVideoControllerUpdate() {
    if (!mounted) {
      return;
    }
    if (initialized != controller!.value.isInitialized) {
      initialized = controller!.value.isInitialized;
      setState(() {});
    }
  }

  @override
  void initState() {
    super.initState();
    controller!.addListener(_onVideoControllerUpdate);
  }

  @override
  void dispose() {
    controller!.removeListener(_onVideoControllerUpdate);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (initialized) {
      return Center(
        child: AspectRatio(
          aspectRatio: controller!.value.aspectRatio,
          child: VideoPlayer(controller!),
        ),
      );
    } else {
      return Container();
    }
  }
}
